package com.ck.controller.teacher;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ck.domain.Banji;
import com.ck.domain.Exam;
import com.ck.domain.ExamBanji;
import com.ck.service.ExamService;
import com.ck.service.TeacherService;

public class EditUnstartExamBanjiController extends SimpleFormController {
	
	private ExamService examService;
	private TeacherService teacherService;
	
	//设置公共变量，供回显表单时使用
	private List<Banji> banjiList = null;
	private List<ExamBanji> examBanjiList = null;
	
	public void setExamService(ExamService examService) {
		this.examService = examService;
	}
	
	public void setTeacherService(TeacherService teacherService) {
		this.teacherService = teacherService;
	}
	
	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors) throws Exception {
		Integer examID = Integer.parseInt(request.getParameter("examID"));
		Exam exam = examService.gainUnstartExam(examID);

		banjiList = teacherService.gainBanjiList();
		examBanjiList = examService.gainBanjiListForExam(examID);
		
		Map model = new HashMap();
		
		model.put("banjiList", banjiList);
		model.put("examBanjiList", examBanjiList);
		
		return model;
	}

	protected Object formBackingObject(HttpServletRequest request)
	throws Exception {
		Integer examID = Integer.parseInt(request.getParameter("examID"));
		Exam exam = examService.gainUnstartExam(examID);
		return exam;
	}
	
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		
		Integer examID = Integer.parseInt(request.getParameter("examID"));
		String[] banji_array = request.getParameterValues("banji");
		
		Map model = errors.getModel();
		
		//后台校验
		boolean flag = true;
		
		if( banji_array == null || banji_array.length == 0 ){
			model.put("error_banji", "请至少选择一个考试班级");
			flag = false;
		}
		
		//校验不通过
        if(!flag){
    		model.put("banjiList", banjiList);
			return new ModelAndView(getFormView(), model);
		}

		boolean isEditSuccess = examService.editUnstartExamBanji(examID, banji_array, model);
		
		if (isEditSuccess) {
			return new ModelAndView(getSuccessView());
		} else {
			model.put("banjiList", banjiList);
			model.put("examBanjiList", examBanjiList);
			return new ModelAndView(getFormView(), model);
		}
	}
}
